package com.alan.boot.mongo.service;

import com.alan.boot.mongo.entity.FormNoCounter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class FormNoService {
    @Resource
    private MongoTemplate mongoTemplate;

    public Long getLatestCount(String formatter) {
        Query query = new Query();
        query.addCriteria(Criteria.where("formatter").is(formatter));
        Update update = new Update();
        update.inc("count", 1);
        FindAndModifyOptions options = FindAndModifyOptions.options().upsert(true).returnNew(true);
        FormNoCounter currentCounter = mongoTemplate.findAndModify(query, update, options, FormNoCounter.class, "formNoCounters");
        return currentCounter.getCount();
    }



}
